/*
 * Created on 12-nov-2009
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.stefanini.pe.bbva.mbl.in.utils;

/**
 * @author juanpablo
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
import java.util.Iterator;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.validator.LengthValidator;
import javax.faces.validator.Validator;

import org.apache.commons.lang.StringUtils;
 


public class RequiredFieldValidatorPhaseListener implements PhaseListener {

    private final static String REQUIRED_FIELD_ATTRIBUTE_KEY = "requiredMsgKey";
    private final static String LENGHT_FIELD_ATTRIBUTE_KEY = "lengthMsgKey";
    
    private final static int VALIDADOR_REQUERIDO = 1;
    private final static int VALIDADOR_LONGITUD = 2;

    private ResourceBundle resourceBundle;


    public void afterPhase(PhaseEvent event) {    }


    public void beforePhase(PhaseEvent event) {
        FacesContext facesContext = event.getFacesContext();
        UIViewRoot viewRoot = facesContext.getViewRoot();
        initializeResourceBundle(facesContext);
        doCustomFieldValidation(facesContext,viewRoot);
    }


 


    public PhaseId getPhaseId() {
        return PhaseId.PROCESS_VALIDATIONS;
    }

    

    private void initializeResourceBundle(FacesContext facesContext) {
        String messageBundle = facesContext.getApplication().getMessageBundle();
        Locale locale = facesContext.getApplication().getDefaultLocale();
        resourceBundle = ResourceBundle.getBundle(messageBundle,locale);
    }

    

    private void doCustomFieldValidation(
            FacesContext facesContext, UIComponent component) {
        if(component instanceof UIInput) {
            UIInput inputComponent = (UIInput)component;
            if(inputComponent.isRequired()) {
               boolean valid = validateValue(inputComponent);
               if(!valid){
                   inputComponent.setValid(false);
                   addErrorMessage(RequiredFieldValidatorPhaseListener.VALIDADOR_REQUERIDO,facesContext,inputComponent);
                   facesContext.renderResponse();
               }
            }
            if (inputComponent.isValid())
            {	//Customiza el Mensaje para el Validador de Longitud
	            Validator[] validators = inputComponent.getValidators();
	            for(int i=0;i<validators.length;i++) {
	            	if (validators[i] instanceof LengthValidator)
	            	{	            		
		                boolean valid = validateLengthValue(inputComponent,(LengthValidator)validators[i]);
		                if(!valid){
		                    inputComponent.setValid(false);
		                    addErrorMessage(RequiredFieldValidatorPhaseListener.VALIDADOR_LONGITUD,facesContext,inputComponent);
		                    facesContext.renderResponse();
		                }
	            	}
	                
	             }
            }
            
        }   

        for (Iterator iter = component.getChildren().iterator(); iter.hasNext();) {
            UIComponent childComponent = (UIComponent) iter.next();
            doCustomFieldValidation(facesContext,childComponent);
        }
    }

    

    private String getRequiredFieldMsgKey(UIInput inputComponent) {
        String msgKey = (String)inputComponent.getAttributes().
                        get(REQUIRED_FIELD_ATTRIBUTE_KEY);
        return msgKey;
    }
   
    private String getLengthFieldMsgKey(UIInput inputComponent) {
        String msgKey = (String)inputComponent.getAttributes().
                        get(LENGHT_FIELD_ATTRIBUTE_KEY);
        return msgKey;
    }

    private boolean  validateValue(UIInput inputComponent) {
        boolean valid = true;
        Object submittedValue = inputComponent.getSubmittedValue();
        if(submittedValue == null) {
            valid = false;
        } else if(submittedValue instanceof String) {
            valid = !StringUtils.isEmpty((String)submittedValue);
        }
        return valid;
    }

    private boolean  validateLengthValue(UIInput inputComponent,LengthValidator lvalidator) {
        boolean valid = true;
        Object submittedValue = inputComponent.getSubmittedValue();
        
        if((submittedValue != null) && (submittedValue.equals("")!=true) && (submittedValue instanceof String)) {
            if((((String)submittedValue).length()>= lvalidator.getMinimum()) && 
               (((String)submittedValue).length()<= lvalidator.getMaximum()))
            {
            	valid = true;
            }else
            {
            	valid = false;
            }            
        }
        return valid;
    }

    

    private void addErrorMessage(int intTipo,FacesContext facesContext, UIInput component) {
    	String msgKey = "";
        String summary = "";
        String detail  = "";
        
    	
    	if(intTipo == RequiredFieldValidatorPhaseListener.VALIDADOR_REQUERIDO)
    	{
	    	msgKey = getRequiredFieldMsgKey(component);
	        summary = getValue("summary." + msgKey);
	        detail  = getValue("detail." + msgKey);
	        
	        if(summary == null) {
	            summary = resourceBundle.getString("javax.faces.component.UIInput.REQUIRED");
	        }
	        if(detail == null) {
	        	detail = resourceBundle.getString("javax.faces.component.UIInput.REQUIRED");
	        }
    	}
    	
    	if(intTipo == RequiredFieldValidatorPhaseListener.VALIDADOR_LONGITUD)
    	{
	    	msgKey = getLengthFieldMsgKey(component);
	        summary = getValue("summary." + msgKey);
	        detail  = getValue("detail." + msgKey);
	        
	        if(summary == null) {
	            summary = resourceBundle.getString("javax.faces.component.UIInput.LENGHT");
	        }
	        if(detail == null) {
	        	detail = resourceBundle.getString("javax.faces.component.UIInput.LENGHT");
	        }
    	}
    	
        FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_FATAL,summary,detail);        
        facesContext.addMessage(component.getClientId(facesContext),facesMessage);
    }

    

    private String getValue(String key) {
        try {
            return resourceBundle.getString(key);
        } catch (RuntimeException e) {
            return null;
        }
    }


 


}

